﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Security.Cryptography;

/// <summary>
///RsaDecrypt 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。 
// [System.Web.Script.Services.ScriptService]
public class RsaDecrypt : System.Web.Services.WebService {

    public RsaDecrypt () {

        //如果使用设计的组件，请取消注释以下行 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string Decrypt(string key,string content)
    {
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        key = key.Replace("-----BEGIN RSA PRIVATE KEY-----", "");
        key = key.Replace("-----END RSA PRIVATE KEY-----", "");
        rsa.ImportCspBlob(Convert.FromBase64String(key));
        var data = Convert.FromBase64String(content);
        var newData = rsa.Decrypt(data, false);
        string dd = System.Text.Encoding.GetEncoding("utf-8").GetString(newData);
        rsa.Dispose();
        return dd;
    }

    [WebMethod]
    public string DecryptC(string key, string content)
    {
        //RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        //key = key.Replace("-----BEGIN RSA PRIVATE KEY-----", "");
        //key = key.Replace("-----END RSA PRIVATE KEY-----", "");
        //rsa.ImportCspBlob(Convert.FromBase64String(key));
        //var data = Convert.FromBase64String(content);
        //var newData = rsa.Decrypt(data, false);
        //string dd = System.Text.Encoding.GetEncoding("utf-8").GetString(newData);
        //rsa.Dispose();

        string re = RsaTools.Decrypt(key, content);
        re = re.Replace("\0", "");
        return re;
    }

    [WebMethod]
    public string DecryptEncoding(string key, string content,string encoding)
    {
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        key = key.Replace("-----BEGIN RSA PRIVATE KEY-----", "");
        key = key.Replace("-----END RSA PRIVATE KEY-----", "");
        rsa.ImportCspBlob(Convert.FromBase64String(key));
        var data = Convert.FromBase64String(content);
        var newData = rsa.Decrypt(data, false);
        string dd = System.Text.Encoding.GetEncoding(encoding).GetString(newData);
        dd = dd.TrimEnd('\0');
        rsa.Dispose();
        return dd;
    }
    
}
